#include "ECGDevice.h"
#include "DatabaseManager.h"
#include <QDebug>
#include <QDateTime>
#include <QDir>
#include <cmath>
#include <algorithm>
#include <QThread>

ECGDevice::ECGDevice(QObject *parent) : BioSignalDevice(parent),
    m_serialPort(new QSerialPort(this)),
    m_readTimer(new QTimer(this)),
    m_headerIndex(0),
    m_bufferIndex(0),
    m_batchSize(50)  // 每50个样本处理一次
{
    // 初始化帧头
    m_frameHeader = QByteArray::fromHex("AAFFF1");

    // 初始化通道数据缓冲区
    for (int i = 0; i < CHANNELS; i++) {
        m_channelData[i].reserve(SAMPLE_RATE);
        m_rawEcgAccumulator[i].reserve(PROCESSING_BLOCK_SIZE * 2); // 预留足够的空间
    }

    // 初始化滤波器
    initializeFilters();

    // 初始化滤波器状态变量
    m_notchZ1.resize(CHANNELS);
    m_notchZ2.resize(CHANNELS);
    m_bpZ1.resize(CHANNELS);
    m_bpZ2.resize(CHANNELS);

    // 初始化所有状态变量为0
    for (int i = 0; i < CHANNELS; i++) {
        m_notchZ1[i] = 0;
        m_notchZ2[i] = 0;
        m_bpZ1[i] = 0;
        m_bpZ2[i] = 0;
    }

    // 连接串口信号
    QObject::connect(m_serialPort, &QSerialPort::readyRead, this, &ECGDevice::readSerialData);
    QObject::connect(m_serialPort, &QSerialPort::errorOccurred, this, &ECGDevice::handleSerialError);

    // 初始化数据库工作线程
    m_dbThread = new QThread(this);
    m_dbWorker = new DatabaseWorker();
    m_dbWorker->moveToThread(m_dbThread);

    QObject::connect(m_dbThread, &QThread::started, m_dbWorker, &DatabaseWorker::process);
    QObject::connect(m_dbWorker, &DatabaseWorker::finished, m_dbThread, &QThread::quit);
    QObject::connect(m_dbWorker, &DatabaseWorker::finished, m_dbWorker, &DatabaseWorker::deleteLater);
    QObject::connect(m_dbThread, &QThread::finished, m_dbThread, &QThread::deleteLater);

    m_dbThread->start();

    // 初始化批处理定时器
    m_batchTimer = new QTimer(this);
    m_batchTimer->setInterval(200);  // 200ms处理一次批量数据
    QObject::connect(m_batchTimer, &QTimer::timeout, this, &ECGDevice::processBatchData);
    m_batchTimer->start();
}
ECGDevice::~ECGDevice()
{
    if (m_isAcquiring) {
        stopAcquisition();
    }

    if (m_isConnected) {
        disconnect();
    }

    if (m_dataFile.isOpen()) {
        m_dataFile.close();
    }
    // 停止数据库工作线程
    if (m_dbWorker) {
        m_dbWorker->stop();
    }
    if (m_dbThread) {
        m_dbThread->quit();
        m_dbThread->wait();
    }
}

void ECGDevice::initializeFilters()
{
    // 设置采样率
    const double fs = SAMPLE_RATE;  // 250Hz

    // 修改：调整50Hz陷波器参数，增加Q值以减小带宽
    const double notchFreq = 50.0;  // 50Hz电源干扰
    const double Q = 45.0;  // 增加Q值，使陷波器更窄

    // 计算陷波器系数
    double w0 = 2 * M_PI * notchFreq / fs;
    double alpha = sin(w0) / (2 * Q);

    m_notchB.resize(3);
    m_notchA.resize(3);

    m_notchB[0] = 1;
    m_notchB[1] = -2 * cos(w0);
    m_notchB[2] = 1;

    m_notchA[0] = 1 + alpha;
    m_notchA[1] = -2 * cos(w0);
    m_notchA[2] = 1 - alpha;

    // 归一化
    for (int i = 0; i < m_notchB.size(); i++) {
        m_notchB[i] /= m_notchA[0];
    }
    for (int i = 1; i < m_notchA.size(); i++) {
        m_notchA[i] /= m_notchA[0];
    }
    m_notchA[0] = 1.0;

    // 修改：调整带通滤波器参数，更适合心电信号
    // 心电信号的主要频率范围在4-40Hz之间
    const double lowcut = 0.5;   // 4Hz高通
    const double highcut = 100.0; // 40Hz低通

    // 使用更精确的巴特沃斯滤波器系数
    // 这些系数是通过数字滤波器设计工具计算得到的
    m_bandpassB.resize(3);
    m_bandpassA.resize(3);

    // 0.5-40Hz带通滤波器系数（二阶巴特沃斯）
    m_bandpassB[0] = 0.0800;
    m_bandpassB[1] = 0;
    m_bandpassB[2] = -0.0800;

    m_bandpassA[0] = 1.0000;
    m_bandpassA[1] = -1.8398;
    m_bandpassA[2] = 0.8598;

    qDebug() << "滤波器初始化完成";
}


QVector<double> ECGDevice::applyNotchFilter(const QVector<double>& input)
{
    QVector<double> output(input.size());

    // 使用直接II型结构实现IIR滤波
    double z1 = 0, z2 = 0;

    for (int i = 0; i < input.size(); i++) {
        // 计算输出
        output[i] = m_notchB[0] * input[i] + z1;

        // 更新状态变量
        z1 = m_notchB[1] * input[i] - m_notchA[1] * output[i] + z2;
        z2 = m_notchB[2] * input[i] - m_notchA[2] * output[i];
    }

    return output;
}

QVector<double> ECGDevice::applyBandpassFilter(const QVector<double>& input)
{
    QVector<double> output(input.size());

    // 使用直接II型结构实现IIR滤波
    double z1 = 0, z2 = 0;

    for (int i = 0; i < input.size(); i++) {
        // 计算输出
        output[i] = m_bandpassB[0] * input[i] + z1;

        // 更新状态变量
        z1 = m_bandpassB[1] * input[i] - m_bandpassA[1] * output[i] + z2;
        z2 = m_bandpassB[2] * input[i] - m_bandpassA[2] * output[i];
    }

    return output;
}

QVector<double> ECGDevice::lfilter(const QVector<double>& b, const QVector<double>& a, const QVector<double>& x)
{
    int n = x.size();
    QVector<double> y(n, 0.0);
    QVector<double> zi(qMax(b.size(), a.size()) - 1, 0.0);

    for (int i = 0; i < n; i++) {
        double sum = 0.0;

        // 计算输入部分
        for (int j = 0; j < b.size(); j++) {
            if (i - j >= 0)
                sum += b[j] * x[i - j];
        }

        // 计算反馈部分
        for (int j = 1; j < a.size(); j++) {
            if (i - j >= 0)
                sum -= a[j] * y[i - j];
        }

        y[i] = sum / a[0];
    }

    return y;
}

QVector<double> ECGDevice::padSignal(const QVector<double>& x, int padlen)
{
    int n = x.size();
    QVector<double> padded(n + 2 * padlen);

    // 填充左侧
    for (int i = 0; i < padlen; i++) {
        padded[i] = x[padlen - i - 1];
    }

    // 复制原始信号
    for (int i = 0; i < n; i++) {
        padded[padlen + i] = x[i];
    }

    // 填充右侧
    for (int i = 0; i < padlen; i++) {
        padded[padlen + n + i] = x[n - i - 1];
    }

    return padded;
}

QVector<double> ECGDevice::filtfilt(const QVector<double>& b, const QVector<double>& a, const QVector<double>& x)
{
    if (x.isEmpty()) {
        return QVector<double>();
    }

    // 确定填充长度
    int padlen = qMax(b.size(), a.size()) * 3;

    // 填充信号
    QVector<double> padded = padSignal(x, padlen);

    // 正向滤波
    QVector<double> y = lfilter(b, a, padded);

    // 反转信号
    std::reverse(y.begin(), y.end());

    // 反向滤波
    y = lfilter(b, a, y);

    // 再次反转信号
    std::reverse(y.begin(), y.end());

    // 提取有效部分
    return QVector<double>(y.begin() + padlen, y.begin() + padlen + x.size());
}

QVector<double> ECGDevice::filterEcgData(const QVector<double>& input)
{
    // 应用陷波滤波器去除50Hz电源干扰
    QVector<double> notchFiltered = filtfilt(m_notchB, m_notchA, input);

    // 应用带通滤波器
    QVector<double> bandpassFiltered = filtfilt(m_bandpassB, m_bandpassA, notchFiltered);

    return bandpassFiltered;
}

bool ECGDevice::connect()
{
    if (m_isConnected) {
        qDebug() << "ECG设备已连接";
        return true;
    }

    qDebug() << "正在连接ECG设备...";

    // 设置串口参数
    m_serialPort->setPortName("COM4");
    m_serialPort->setBaudRate(460800);
    m_serialPort->setDataBits(QSerialPort::Data8);
    m_serialPort->setStopBits(QSerialPort::OneStop);
    m_serialPort->setParity(QSerialPort::NoParity);
    m_serialPort->setFlowControl(QSerialPort::NoFlowControl);

    // 打开串口
    if (!m_serialPort->open(QIODevice::ReadWrite)) {
        QString errorMsg = QString("无法打开串口COM4: %1").arg(m_serialPort->errorString());
        qDebug() << errorMsg;
        emit errorOccurred(errorMsg);
        return false;
    }

    // 重置ADS1298
    if (!resetADS1298()) {
        m_serialPort->close();
        return false;
    }

    m_isConnected = true;
    emit connectionStatusChanged(true);
    qDebug() << "ECG设备连接成功";
    return true;
}

bool ECGDevice::disconnect()
{
    if (!m_isConnected) {
        return true;
    }

    if (m_isAcquiring) {
        stopAcquisition();
    }

    // 关闭串口
    m_serialPort->close();

    m_isConnected = false;
    emit connectionStatusChanged(false);
    qDebug() << "ECG设备已断开连接";
    return true;
}

bool ECGDevice::startAcquisition()
{
    if (!m_isConnected) {
        qDebug() << "ECG设备未连接，无法开始采集";
        return false;
    }

    if (m_isAcquiring) {
        qDebug() << "ECG设备已在采集数据";
        return true;
    }

    // 清空缓冲区
    m_receiveBuffer.clear();
    m_headerIndex = 0;
    m_bufferIndex = 0;

    for (int i = 0; i < CHANNELS; i++) {
        m_channelData[i].clear();
        m_rawEcgAccumulator[i].clear();
        m_filteredOutputQueue[i].clear();

        // 重置滤波器状态变量
        m_notchZ1[i] = 0;
        m_notchZ2[i] = 0;
        m_bpZ1[i] = 0;
        m_bpZ2[i] = 0;
    }

    // 发送开始采集命令
    if (!sendCommand(0x08)) { // START命令
        m_dataFile.close();
        return false;
    }

    m_isAcquiring = true;
    emit acquisitionStatusChanged(true);
    qDebug() << "ECG数据采集已开始";
    return true;
}
bool ECGDevice::stopAcquisition()
{
    if (!m_isAcquiring) {
        return true;
    }

    // 发送停止采集命令
    sendCommand(0x0A); // STOP命令

    // 关闭数据文件
    if (m_dataFile.isOpen()) {
        m_dataFile.close();
    }

    m_isAcquiring = false;
    emit acquisitionStatusChanged(false);
    qDebug() << "ECG数据采集已停止";
    return true;
}
QString ECGDevice::getDeviceInfo() const
{
    return "ECG设备 (ADS1298) - " + QString(m_isConnected ? "已连接" : "未连接");
}


bool ECGDevice::sendCommand(unsigned char command)
{
    if (!m_serialPort->isOpen()) {
        return false;
    }

    QByteArray data;
    data.append(static_cast<char>(command));

    qint64 bytesWritten = m_serialPort->write(data);
    if (bytesWritten != data.size()) {
        QString errorMsg = QString("发送命令失败: 0x%1").arg(command, 2, 16, QChar('0'));
        qDebug() << errorMsg;
        emit errorOccurred(errorMsg);
        return false;
    }

    m_serialPort->flush();
    qDebug() << QString("命令 0x%1 发送成功").arg(command, 2, 16, QChar('0'));
    return true;
}

bool ECGDevice::resetADS1298()
{
    // 发送复位命令
    if (!sendCommand(0x41)) return false; // WREG | 0x01 (CONFIG1寄存器)
    if (!sendCommand(0x00)) return false; // 写入1个寄存器
    if (!sendCommand(0x06)) return false; // 250Hz (0x06)

    // 等待设置生效 - 增加等待时间确保命令执行完成
    QThread::msleep(20);

    // 设置连续读取数据模式
    if (!sendCommand(0x10)) return false; // RDATAC

    // 增加调试输出
    qDebug() << "ADS1298已重置，采样率设置为250Hz";

    // 再次等待确保命令生效
    QThread::msleep(10);

    return true;
}

int32_t ECGDevice::parseECGData(const QByteArray &data, int offset)
{
    if (offset + 3 >= data.size()) {
        return 0;
    }

    uint8_t b0 = static_cast<uint8_t>(data.at(offset));
    uint8_t b1 = static_cast<uint8_t>(data.at(offset + 1));
    uint8_t b2 = static_cast<uint8_t>(data.at(offset + 2));
    uint8_t b3 = static_cast<uint8_t>(data.at(offset + 3));

    return static_cast<int32_t>(b0 | (b1 << 8) | (b2 << 16) | (b3 << 24));
}

double ECGDevice::convertToVoltage(int32_t adcValue)
{
    return (adcValue * LSB) / GAIN;
}

void ECGDevice::calculateChecksum(const QByteArray &data, int length, uint8_t *sumcheck, uint8_t *addcheck)
{
    *sumcheck = 0;
    *addcheck = 0;

    for (int i = 0; i < length && i < data.size(); i++) {
        *sumcheck += static_cast<uint8_t>(data.at(i));
        *addcheck += *sumcheck;
    }
}

void ECGDevice::parseLeadOffStatus(uint8_t leadOffHigh, uint8_t leadOffLow)
{
    QStringList disconnectedLeads;
    bool hasLeadOff = false;

    if (leadOffHigh == 0xFF && leadOffLow == 0x00) {
        disconnectedLeads << "RL";
        hasLeadOff = true;
    } else {
        if (leadOffHigh == 0xFF) {
            disconnectedLeads << "所有P通道 (LA, LL, V1-V6)";
            hasLeadOff = true;
        } else {
            if (leadOffHigh & (1 << 0)) {
                disconnectedLeads << "LA (左臂电极)";
                hasLeadOff = true;
            }
            if (leadOffHigh & (1 << 1)) {
                disconnectedLeads << "LL (左腿电极)";
                hasLeadOff = true;
            }

            for (int i = 2; i < 8; i++) {
                if (leadOffHigh & (1 << i)) {
                    disconnectedLeads << QString("V%1 (胸导联 %2)").arg(i - 1).arg(i - 1);
                    hasLeadOff = true;
                }
            }
        }

        for (int i = 0; i < 2; i++) {
            if (leadOffLow & (1 << i)) {
                disconnectedLeads << QString("%1N").arg(i + 1);
                hasLeadOff = true;
            }
        }
    }

    if (hasLeadOff) {
        // 注释掉导联脱落信息的输出
        // QString message = "导联脱落: " + disconnectedLeads.join(", ");
        // qDebug() << message;
        // emit errorOccurred(message);

        // 如果正在采集数据，发送导联脱落信号
        if (m_isAcquiring) {
            emit leadOffDetected(true);
        }
    } else if (m_isAcquiring) {
        // 如果没有导联脱落，并且之前有过导联脱落，发送导联恢复信号
        emit leadOffDetected(false);
    }
}

bool ECGDevice::parseECGFrame(const QByteArray &frame)
{
    if (frame.size() < 40) {
        qDebug() << "帧长度不足:" << frame.size();
        return false;
    }

    // 校验和检查
    uint8_t sumcheck, addcheck;
    calculateChecksum(frame, 38, &sumcheck, &addcheck);

    uint8_t frameSumcheck = static_cast<uint8_t>(frame.at(38));
    uint8_t frameAddcheck = static_cast<uint8_t>(frame.at(39));

    if (sumcheck != frameSumcheck || addcheck != frameAddcheck) {
        qDebug() << "校验和错误 计算值:" << sumcheck << addcheck
                 << "帧值:" << frameSumcheck << frameAddcheck;
        return false;
    }

    // 解析导联脱落状态 - 保持函数调用，但不输出信息
    uint8_t leadOffHigh = static_cast<uint8_t>(frame.at(36));
    uint8_t leadOffLow = static_cast<uint8_t>(frame.at(37));
    parseLeadOffStatus(leadOffHigh, leadOffLow);

    // 解析8个通道的数据
    QVector<double> rawChannelValues(CHANNELS);
    QVector<double> filteredValues(CHANNELS);

    // 调试输出原始帧数据
    //qDebug() << "解析通道数据:";

    // 第一轮解析，检测数据模式和有效通道
    for (int i = 0; i < CHANNELS; i++) {
        int32_t adcValue = parseECGData(frame, 4 + i * 4);
        double voltage = convertToVoltage(adcValue);

        // 将电压值从伏特(V)转换为毫伏(mV)
        voltage = voltage * 1000.0; // 转换为毫伏

        rawChannelValues[i] = voltage;

        // 调试输出每个通道的原始值
        //qDebug() << "通道" << i << "ADC值:" << adcValue << "电压:" << voltage << "mV";
    }

    // 实时滤波处理 - 对每个通道的样本直接应用滤波器
    for (int i = 0; i < CHANNELS; i++) {
        filteredValues[i] = filterEcgSample(rawChannelValues[i], i);
    }

    // 保存原始数据的副本，用于后续写入数据库
    QVector<double> originalRawValues = rawChannelValues;

    // 更新通道数据缓冲区
    for (int i = 0; i < CHANNELS; i++) {
        QMutexLocker locker(&m_dataMutex);
        m_channelData[i].append(filteredValues[i]);

        // 保持缓冲区大小不超过采样率
        while (m_channelData[i].size() > SAMPLE_RATE) {
            m_channelData[i].removeFirst();
        }
    }

    // 获取当前时间戳
    qint64 timestamp = QDateTime::currentMSecsSinceEpoch();

    // 写入数据文件
    if (m_dataFile.isOpen()) {
        m_dataStream << timestamp << ",";

        for (int i = 0; i < CHANNELS; i++) {
            m_dataStream << filteredValues[i];
            if (i < CHANNELS - 1) {
                m_dataStream << ",";
            }
        }
        m_dataStream << "\n";

        // 确保数据立即写入文件
        m_dataStream.flush();
    }

    // 修改：使用批处理机制，将数据添加到批处理缓冲区
    static int batchCounter = 0;

    // 添加批处理计数，减少信号发送频率
    if (++batchCounter >= 5) {  // 每5帧数据发送一次信号，而不是每一帧
        // 保存数据到批处理缓冲区
        m_dbBatchBuffer.append(filteredValues);
        m_dbBatchTimestamps.append(timestamp);

        // 发送数据就绪信号 - 为每个通道单独发送数据
        for (int i = 0; i < CHANNELS; i++) {
            QVector<double> channelBatch;
            channelBatch.append(filteredValues[i]);
            emit dataReady(channelBatch, i, timestamp);
        }

        // 同时发送所有通道的最新数据点
        emit allChannelsDataReady(filteredValues, timestamp);

        // 重置批处理计数器
        batchCounter = 0;
    }

    return true;
}


void ECGDevice::readSerialData()
{
    if (!m_isAcquiring || !m_serialPort->isOpen()) {
        return;
    }

    QMutexLocker locker(&m_dataMutex1); // 添加互斥锁保护

    // 读取可用数据
    QByteArray data = m_serialPort->readAll();

    // 调试输出接收到的数据大小
    if (!data.isEmpty()) {
        qDebug() << "接收到ECG数据:" << data.size() << "字节";
    }

    // 处理每一个字节
    for (int i = 0; i < data.size(); i++) {
        char currentByte = data.at(i);

        if (m_headerIndex < 3) {
            // 寻找帧头
            if (currentByte == m_frameHeader.at(m_headerIndex)) {
                m_receiveBuffer.append(currentByte);
                m_headerIndex++;

                if (m_headerIndex == 3) {
                    m_bufferIndex = 3;
                }
            } else {
                m_receiveBuffer.clear();
                m_headerIndex = 0;

                // 检查当前字节是否是帧头的第一个字节
                if (currentByte == m_frameHeader.at(0)) {
                    m_receiveBuffer.append(currentByte);
                    m_headerIndex = 1;
                }
            }
        } else {
            // 收集帧数据
            m_receiveBuffer.append(currentByte);
            m_bufferIndex++;

            // 完整帧接收完毕
            if (m_bufferIndex >= 40) {
                // 解析帧数据
                if (parseECGFrame(m_receiveBuffer)) {
                    //qDebug() << "帧解析成功";
                } else {
                    //qDebug() << "帧解析失败";
                }

                // 重置缓冲区，准备接收下一帧
                m_receiveBuffer.clear();
                m_headerIndex = 0;
                m_bufferIndex = 0;
            }
        }
    }
}


void ECGDevice::handleSerialError(QSerialPort::SerialPortError error)
{
    if (error == QSerialPort::NoError) {
        return;
    }

    QString errorMsg = QString("串口错误: %1").arg(m_serialPort->errorString());
    qDebug() << errorMsg;
    emit errorOccurred(errorMsg);

    if (m_isAcquiring) {
        stopAcquisition();
    }

    if (m_isConnected && (error == QSerialPort::ResourceError ||
                          error == QSerialPort::PermissionError ||
                          error == QSerialPort::DeviceNotFoundError)) {
        disconnect();
    }
}

QVector<double> ECGDevice::getChannelData(int channel) const
{
    if (channel < 0 || channel >= CHANNELS) {
        return QVector<double>();
    }

    // 创建一个副本以避免在锁外修改数据
    QMutexLocker locker(&m_dataMutex);
    return m_channelData[channel];
}

void ECGDevice::processDatabaseQueue(const QVector<QVector<double>>& batchData,
                                     const QVector<QVector<double>>& batchRawData,
                                     qint64 batchTimestamp)
{
    // 获取数据库管理器实例
    DatabaseManager* dbManager = DatabaseManager::getInstance();
    if (dbManager) {
        for (int i = 0; i < batchData.size(); i++) {
            // 插入滤波后数据，并获取ID
            int filteredDataId = dbManager->insertEcgData(batchData[i], -1, batchTimestamp + i * 4); // 假设4ms间隔

            // 如果插入成功，插入对应的原始数据
            if (filteredDataId > 0 && i < batchRawData.size()) {
                dbManager->insertEcgRawData(batchRawData[i], batchTimestamp + i * 4, filteredDataId);
            }
        }
    }
}


// 新增：实时滤波器方法 - 对单个样本应用陷波滤波
double ECGDevice::applyNotchFilterSample(double sample, int channel) {
    if (channel < 0 || channel >= CHANNELS) {
        return sample;
    }

    // 使用直接II型结构实现IIR滤波（单样本）
    double output = m_notchB[0] * sample + m_notchZ1[channel];

    // 更新状态变量
    m_notchZ1[channel] = m_notchB[1] * sample - m_notchA[1] * output + m_notchZ2[channel];
    m_notchZ2[channel] = m_notchB[2] * sample - m_notchA[2] * output;

    return output;
}

// 新增：实时滤波器方法 - 对单个样本应用带通滤波
double ECGDevice::applyBandpassFilterSample(double sample, int channel) {
    if (channel < 0 || channel >= CHANNELS) {
        return sample;
    }

    // 使用直接II型结构实现IIR滤波（单样本）
    double output = m_bandpassB[0] * sample + m_bpZ1[channel];

    // 更新状态变量
    m_bpZ1[channel] = m_bandpassB[1] * sample - m_bandpassA[1] * output + m_bpZ2[channel];
    m_bpZ2[channel] = m_bandpassB[2] * sample - m_bandpassA[2] * output;

    return output;
}

// 新增：实时滤波器方法 - 完整的滤波链
double ECGDevice::filterEcgSample(double sample, int channel) {
    if (channel < 0 || channel >= CHANNELS) {
        return sample;
    }

    // 首先应用陷波滤波器去除50Hz电源干扰
    double notchFiltered = applyNotchFilterSample(sample, channel);

    // 然后应用带通滤波器
    double bandpassFiltered = applyBandpassFilterSample(notchFiltered, channel);

    return bandpassFiltered;
}


// 添加批处理方法
void ECGDevice::processBatchData()
{
    // 如果没有数据，直接返回
    if (m_dbBatchBuffer.isEmpty()) {
        return;
    }

    // 复制当前批次数据，然后清空缓冲区
    QVector<QVector<double>> batchData;
    QVector<qint64> batchTimestamps;

    {
        // 缩小锁的范围，只在复制和清空缓冲区时锁定
        QMutexLocker locker(&m_dataMutex);
        batchData = m_dbBatchBuffer;
        batchTimestamps = m_dbBatchTimestamps;
        m_dbBatchBuffer.clear();
        m_dbBatchTimestamps.clear();
    }

    // 获取数据库管理器实例
    DatabaseManager* dbManager = DatabaseManager::getInstance();
    int currentSubjectId = dbManager ? dbManager->getCurrentSubjectId() : -1;

    // 将数据库操作提交到工作线程
    for (int i = 0; i < batchData.size(); i++) {
        if (i < batchTimestamps.size()) {
            // 减少日志输出，不再每次都输出"解析通道数据:"
            EcgInsertTask* task = new EcgInsertTask(batchData[i], batchTimestamps[i], currentSubjectId);
            m_dbWorker->addTask(task);
        }
    }
}


void ECGDevice::moveToThread(QThread* thread)
{
    // 将设备对象移动到指定线程
    QObject::moveToThread(thread);

    // 将串口对象也移动到同一线程
    m_serialPort->moveToThread(thread);

    m_workerThread = thread;
}

void ECGDevice::processInThread()
{
    // 这个方法会在设备线程中被调用
    // 处理串口数据
    if (m_serialPort->bytesAvailable() > 0) {
        readSerialData();
    }
}
